﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;



namespace DocumentsTagger.UI
{
    public partial class DocViewer : UserControl, IViewer
    {
        private string m_LoadedData = string.Empty;
        public event ControlLoadedHandler ControlLoaded;

        public void LoadData(string fileName)
        {
            Thread t = new Thread(new ParameterizedThreadStart(bg_DoWork));
            t.Name = "DocViewerThread";
            t.SetApartmentState(ApartmentState.STA);
            t.Start(fileName);
        }

        /// <summary>
        /// Initialize the control
        /// </summary>
        public DocViewer()
        {
            InitializeComponent();
        }

        /// <summary>
        /// will be run when the loading thread is done getting the data from the file itself.
        /// </summary>
        void bg_RunWorkerCompleted()
        {
            if (this.InvokeRequired)
            {
                Action act = () => bg_RunWorkerCompleted();
                this.Invoke(act, null);
            }
            else
            {
                try
                {
                    this.richTextBox1.Rtf = m_LoadedData;
                }
                catch
                { 
                    // do nothing
                }
                onControlLoaded();
            }
        }

        /// <summary>
        /// this is the event trigger.
        /// </summary>
        private void onControlLoaded()
        {
            if (ControlLoaded != null)
            {
                ControlLoaded();
            }
        }

        /// <summary>
        /// this is function gets the data from the file. 
        /// happens in a diffrent thread from the UI!
        /// </summary>
        /// <param name="param"></param>
        void bg_DoWork(object param)
        {
            string fileName = (string)param;
            m_LoadedData = GetDocData(fileName);
            bg_RunWorkerCompleted();
        }

        private String GetDocData(string FileName)
        {
            String fileData = string.Empty;
            try
            {
                Microsoft.Office.Interop.Word._Application appWord = null;
                Microsoft.Office.Interop.Word._Document docWord = null;

                Object filename = FileName;
                Object ConfirmConversions = System.Reflection.Missing.Value;
                Object ReadOnly = true;
                Object AddToRecentFiles = System.Reflection.Missing.Value;
                Object PasswordDocument = System.Reflection.Missing.Value;
                Object PasswordTemplate = System.Reflection.Missing.Value;
                Object Revert = System.Reflection.Missing.Value;
                Object WritePasswordDocument = System.Reflection.Missing.Value;
                Object WritePasswordTemplate = System.Reflection.Missing.Value;
                Object Format = System.Reflection.Missing.Value;
                Object Encoding = System.Reflection.Missing.Value;
                Object Visible = false;

                Object saveChanges = false;
                Object originalFormat = null;
                Object routeDoc = null;
                try
                {
                    try
                    {
                        appWord = new Microsoft.Office.Interop.Word.Application();
                        appWord.Visible = false;
                        docWord = appWord.Documents.Open(ref filename, ref ConfirmConversions, ref ReadOnly,
                                          ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate,
                                          ref Revert, ref WritePasswordDocument, ref WritePasswordTemplate,
                                          ref Format, ref Encoding, ref Visible);
                        if (docWord.ProtectionType == Microsoft.Office.Interop.Word.WdProtectionType.wdNoProtection)
                        {
                            docWord.ActiveWindow.Selection.WholeStory();
                            docWord.ActiveWindow.Selection.Copy();
                            IDataObject data = Clipboard.GetDataObject();
                            fileData = data.GetData(DataFormats.Rtf).ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        //docWord.ActiveWindow.Close(ref saveChanges, ref routeDoc);
                        docWord.Close(ref saveChanges, ref originalFormat, ref routeDoc);
                        appWord.Quit(ref saveChanges, ref originalFormat, ref routeDoc);
                    }
                }
                catch (Exception ex)
                {
                    appWord.Quit(ref saveChanges, ref originalFormat, ref routeDoc);
                }
            }
            catch
            { 
                // do nothing
            }
            return fileData;
        }
        
        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
